package com.newenergy.wisehome.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.helper.LogHelper;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.ui.adapter.SelectHEAAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.yokeyword.fragmentation.ISupportFragment;

/**
 * 照明分享中选择组
 */
public class SelectHEAFragment extends BaseFragment {

    private static String ARG_SELECTHEA = "arg_selecthea";
    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.tv_back)
    TextView mTvBack;
    @BindView(R.id.tv_page)
    TextView mTvPage;

    @BindView(R.id.btn_add)
    Button mBtnAdd;

    @BindView(R.id.btn_select_all)
    Button mBtnSelectAll;

    @BindView(R.id.btn_share)
    Button mBtnShare;

    @BindView(R.id.tv_empty)
    TextView mTvEmpty;

    @BindView(R.id.recyclerView)
    EasyRecyclerView mRecyclerView;
    @BindView(R.id.rl_empty)
    RelativeLayout mRlEmpty;

    private SelectHEAAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;

    private List<DeviceCategory> mSelectedGroups = new ArrayList<>();


    private Family mCurrFamily;

    public SelectHEAFragment() {
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_select_hea;
    }


    public static ISupportFragment newInstance(Family currItem) {
        Bundle args = new Bundle();
        args.putParcelable(ARG_SELECTHEA, currItem);
        SelectHEAFragment fragment = new SelectHEAFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void init(View rootView) {
        mBtnAdd.setVisibility(View.VISIBLE);
        mBtnAdd.setBackgroundResource(R.drawable.btn_share);
        initRecycleView();

        mCurrFamily = getArguments().getParcelable(ARG_SELECTHEA);

        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        List<DeviceCategory> groups = deviceCategoryDao.getFamilyHEA(mCurrFamily.getFamilyId());
        mAdapter.refreshData(groups);
        showEmptyView();
        mTvPage.setText(getString(R.string.btn_share_qrcode));

    }

    @Override
    public void onResume() {
        super.onResume();

    }

    private void showEmptyView() {
        boolean isEmpty = false;
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        List<DeviceCategory> groups = deviceCategoryDao.getFamilyHEA(mCurrFamily.getFamilyId());
        if (groups == null || groups.size() < 1) isEmpty = true;
        mRlEmpty.setVisibility(isEmpty ? View.VISIBLE : View.GONE);
        mBtnSelectAll.setVisibility(isEmpty ? View.GONE : View.VISIBLE);
        mRecyclerView.setVisibility(isEmpty ? View.GONE : View.VISIBLE);
    }

    private void initRecycleView() {
        Context context = getContext();
        mAdapter = new SelectHEAAdapter(context);
        mRecyclerView.setAdapter(mAdapter);
        mLayoutManager = new LinearLayoutManager(context);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter.setOnItemClickListener(position -> {
            DeviceCategory item = mAdapter.getItem(position);
            boolean checked = !item.isChecked();
            item.setChecked(checked);
            mAdapter.notifyItemChanged(position);

        });
    }

    @OnClick({R.id.btn_back, R.id.tv_back, R.id.btn_add, R.id
            .btn_select_all,R.id.btn_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                doBack();
                break;

            case R.id.tv_back:
                doBack();
                break;

            case R.id.btn_add:
                shareFamilyGroup();
                break;

            case R.id.btn_select_all:
                selectAllGroup();
                break;

            case R.id.btn_share:
                shareFamilyGroup();
                break;
        }
    }

    private void selectAllGroup() {
        boolean selected = !mBtnSelectAll.isSelected();
        mBtnSelectAll.setSelected(selected);

        List<DeviceCategory> allData = mAdapter.getAllData();
        for (DeviceCategory group : allData) {
            group.setChecked(selected);
        }
        mAdapter.notifyDataSetChanged();
    }

    private void shareFamilyGroup() {
        //[ # & 都已被占用
        LogHelper.i("goto QRCodeFragment");
        getSelectedGroups();
        if (mCurrFamily == null || mSelectedGroups.size() < 1) {
//            ToastUtil.myToast(getString(R.string.no_select_group));
            showDialog(getString(R.string.select_one_or_more));
            mHandler.sendEmptyMessageDelayed(2, 1000);
            return;
        }
        StringBuilder builder = new StringBuilder();

        builder.append("7202").append("[");
        builder.append(mCurrFamily.toQRContent());
        for (DeviceCategory group : mSelectedGroups) {
            builder.append(group.toQRContent()).append("#");
        }

        String qrContent = builder.toString();
        int length = qrContent.length();
        qrContent = qrContent.substring(0, length - 1);

        start(QRCodeFragment.newInstance(qrContent));

    }

    public void getSelectedGroups() {
        mSelectedGroups.clear();
        List<DeviceCategory> allDatas = mAdapter.getAllData();
        for (DeviceCategory group : allDatas) {
            if (group.isChecked()) mSelectedGroups.add(group);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 2:
                    dissDialog();
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }
}
